import React, { useEffect, useRef, useState } from 'react';
import TableDataBlock from '@/components/TableDataBlock';
import Details from './../details';
import FormSet from './../SetForm';
import { connect } from 'umi';
import PopImgShow from '@/components/PopImgShow';
import { categoryType_status } from '@/common/contact';
import { useUpdateEffect } from 'ahooks'
import { Tooltip, notification } from 'antd'
import { AuditOutlined, FileTextOutlined } from '@ant-design/icons'
import Indentation from '@/components/Indentation';
import CodeModel from './../CodeModel';
const Table = (props) => {
  const { loading, list, dispatch, activeTabKey, selectedKeys, categoryList, childRef } = props;
  const [modelVisible, setModelVisible] = useState(false)
  const copyList = e => {
    const textToCopy = e
    // 创建一个虚拟input元素
    const input = document.createElement('input')
    input.value = textToCopy
    document.body.appendChild(input)
    // 选择输入框的内容
    input.select()
    input.setSelectionRange(0, 99999) // 兼容移动设备
    // 执行复制操作
    document.execCommand('copy')
    // 移除虚拟input元素
    document.body.removeChild(input)
    // 可以显示一条消息或者执行其他操作
    notification.success({
      message: '温馨提示',
      description: `复制成功`,
    })
  }
  useUpdateEffect(() => {
    handleCallback()
  }, [
    activeTabKey, selectedKeys
  ])
  const fetchShareInfo = (record, callback) => {
    const { id } = record
    dispatch({
      type: 'liveStreaming/fetchGetShareInfo',
      payload: {
        shareId: id,
        shareType: 'material',

        organizationId: window.localStorage.getItem(
          'organizationId',
        )
      },
      callback: (e) => {
        const { shareInfo } = e
        const {
          wechatUrl
        } = shareInfo
        copyList(wechatUrl)
      }
    })

  }
  const fetchShareCode = (record) => {
    const { id } = record
    dispatch({
      type: 'liveStreaming/fetchGetShareInfo',
      payload: {
        shareId: id,
        shareType: 'material',
        organizationId: window.localStorage.getItem(
          'organizationId',
        )
      },
      callback: async (e) => {
        const { shareInfo } = e
        setModelVisible({
          show: true,
          details: shareInfo
        })
      }
    })

  }
  const btnExtra = [
    {
      text: '新增素材',
      onClick: () => {
        setVisible({
          show: true,
          detail: {
            categoryId: findParentIds(categoryList, selectedKeys.toString()).reverse(),
          }
        })
      }

    },
  ];
  const findParentIds = (data, childId, result = []) => {
    for (let i = 0; i < data.length; i++) {
      const item = data[i];
      if (item.id == childId) {
        result.push(item.id);
        if (item.parentId) {
          findParentIds(data, item.parentId, result);
        }
        break;
      } else if (item.subMaterialCategoryList) {
        findParentIds(item.subMaterialCategoryList, childId, result);
        if (result.length > 0 && item.id) {
          result.push(item.id);
          break;
        }
      }
    }
    return result;
  };
  const [visible, setVisible] = useState(false);
  const [visibleDetails, setVisibleDetails] = useState(false);
  const searchItems = [
    { label: '关键词', name: 'keyword' },
    {
      label: '资源渠道',
      name: 'materialType',
      type: 'select',
      select: {
        self: '自己制作',
        other: '其他渠道',
      },
    },
    {
      label: '状态',
      name: 'status',
      type: 'select',
      select: {
        0: '禁用',
        1: '启用',
      },
    },
    {
      label: '分享状态',
      name: 'shareFlag',
      type: 'select',
      select: {
        0: '不允许',
        1: '允许',
      },
    },
  ];

  const handleCallback = () => {
    childRef.current.fetchGetData();
  };
  function getFileExtension(fileName) {
    // 使用正则表达式匹配文件名中的后缀部分
    const regex = /(?:\.([^.]+))?$/;
    const result = regex.exec(fileName);

    // 提取匹配到的后缀，如果没有后缀则返回空字符串
    const extension = result ? result[1] : '';

    return extension;
  }

  // 示例用法

  const renderContent = (url, type, falg = true) => {
    if (type === 'image') {
      return <PopImgShow width={30} url={url}></PopImgShow>
    } else if (type === 'video') {
      return <PopImgShow width={30} url={url}></PopImgShow>
    } else if (type === 'voice') {
      return <Tooltip title={url}>
        <a style={{ fontSize: 24 }} target="_blank" href={url}><AuditOutlined></AuditOutlined></a>
      </Tooltip>
    }
    else if (type === 'ebook') {
      return <Tooltip title={url}>
        <a style={{ fontSize: 24 }} target="_blank" href={url}><FileTextOutlined></FileTextOutlined></a>
      </Tooltip>
    } else {
      const fileExtension = getFileExtension(url);
      const color = {
        pptx: '#2db7f5',
        ppt: '#87d068',
        docx: '#108ee9',
        doc: '#2db7f5',
        xls: '#87d068',
        xlsx: '#108ee9',
        pdf: '#2db7f5',
        csv: '#87d068',
        xlsm: '#2db7f5',
        txt: '#87d068',
        zip: '#2db7f5',
        vtt: '#f50'
      }[fileExtension]
      console.log(color)
      return <Tooltip title={url}><div style={{ background: color || 'red', color: '#Ffffff', width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto' }}>{fileExtension}</div></Tooltip>
    }
  }

  const getColumns = [
    {
      title: '素材名称',
      dataIndex: 'materialName',
    },
    {
      title: categoryType_status[activeTabKey],
      dataIndex: 'content',
      render: (e, record) => {
        const { contentType, cover } = record
        if (contentType === 'video') {
          const { url } = JSON.parse(cover);
          return renderContent(url, contentType);
        }
        const { url } = JSON.parse(e);
        return renderContent(url, contentType);
      },
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
    },
    {
      title: '创建人',
      dataIndex: 'createAdminName',
    },
    {
      title: '是否允许分享',
      dataIndex: 'shareFlag',
      render: (e, record) => {
        const { shareFlag, categoryShareFlag, } = record
        if (shareFlag === '2') {
          if (categoryShareFlag === '1') {
            return '允许'
          }
          return '不允许'
        }
        else {
          if (e === '1') {
            return '允许'
          }
          return '不允许'
        }

      }
    },
    {
      title: '是否允许下载',
      dataIndex: 'downloadFlag',
      render: (e, record) => {
        const { downloadFlag, categoryDownloadFlag, } = record
        if (downloadFlag === '2') {
          if (categoryDownloadFlag === '1') {
            return '允许'
          }
          return '不允许'
        }
        else {
          if (e === '1') {
            return '允许'
          }
          return '不允许'
        }

      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (e) => {
        return {
          0: '下架',
          1: '上架',
        }[e];
      },
    },
    {
      title: '素材描述',
      dataIndex: 'description',
      render: (e) => {
        return <Indentation width={100} str={e}></Indentation>;
      },
    },

    {
      type: 'handle',
      width: 200,
      dataIndex: 'id',
      render: (val, record) => [
        {
          title: '查看详情',
          auth: true,
          type: 'edit',
          click: () =>
            dispatch({
              type: 'liveStreaming/fetchGetMaterialDetail',
              payload: { id: val },
              callback: (e) => {
                setVisibleDetails({
                  show: true,
                  detail: e,
                });
              },
            }),
        },
        {
          title: '复制链接',

          click: () => {
            fetchShareInfo(record,)
          },
        },
        {
          title: '分享二维码',

          click: () => {
            fetchShareCode(record)
          },
        },
        {
          title: '编辑 ',
          auth: true,
          type: 'edit',
          click: () =>
            dispatch({
              type: 'liveStreaming/fetchGetMaterialDetail',
              payload: { id: val },
              callback: (e) => {
                const { cover, content, contentType, categoryId } = e;
                let contentInfo = JSON.parse(content || '{}');
                let coverInfo = JSON.parse(cover || '{}');
                setVisible({
                  show: true,
                  detail: {
                    ...e,
                    [contentType === 'video' ? 'shiping' : contentType === 'image' ? 'image' : 'otherFile']: [contentInfo.url],
                    cover: coverInfo.url ? [coverInfo.url] : [],
                    categoryId: findParentIds(categoryList, categoryId).reverse(),
                  },
                });
              },
            }),
        },
        {
          title: '禁用',
          auth: true,
          visible: record.status === '1',
          click: () => {
            dispatch({
              type: 'liveStreaming/fakeChangeMaterialStatus',
              payload: {
                id: val,
                status: '0',
              },
              callback: () => {
                handleCallback();
              },
            });
          },
        },
        {
          title: '启用',
          auth: true,
          visible: record.status === '0',
          click: () => {
            dispatch({
              type: 'liveStreaming/fakeChangeMaterialStatus',
              payload: {
                id: val,
                status: '1',
              },
              callback: () => {
                handleCallback();
              },
            });
          },
        },
      ],
    },
  ];
  return (<div>
    <TableDataBlock
      cRef={childRef}
      btnExtra={btnExtra}
      loading={loading}
      searchItems={searchItems}
      params={{ contentType: activeTabKey, categoryId: selectedKeys.toString() }}
      columns={getColumns}
      rowKey={(record) => `${record.id}`}
      dispatchType="liveStreaming/fetchListMaterial"
      {...list}
    ></TableDataBlock>
    <FormSet
      visible={visible}
      onClose={() => {
        setVisible(false);
      }}
      activeTabKey={activeTabKey}
      categoryList={categoryList}
      handleCallback={handleCallback}
    ></FormSet>
    <Details
      renderContent={renderContent}
      visible={visibleDetails}
      onClose={() => {
        setVisibleDetails(false);
      }}
    ></Details>
    <CodeModel visible={modelVisible} onClose={() => setModelVisible(false)}></CodeModel>
  </div>)
}

export default connect(({ loading, liveStreaming }) => ({
  list: liveStreaming.materialList,
  loading: loading.models.liveStreaming,
}))(Table);
